package demo01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author:Mrzhang
 * @Description:模拟服务器端
 * @Date:2019.01.20 16:44
 **/
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(2000);


        System.out.println("服务器准备就绪");

        System.out.println("服务器信息：" + serverSocket.getInetAddress() + "    port:" + serverSocket.getLocalPort());
//        System.out.println("客户端信息：" + serverSocket.getLocalAddress() + "   port:" + socket.getLocalPort());

        //无限循环（多个客户端连接）
        for (; ; ) {
            //等待客户端连接，得到客户端
            Socket client = serverSocket.accept();
            //客户端构建异步线程
            ClientHandler clientHandler = new ClientHandler(client);
            //启动线程
            clientHandler.start();
        }

    }

    /**
     * 客户端消息处理
     */
    private static class ClientHandler extends Thread {
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户连接：" + socket.getInetAddress() + "  port" + socket.getPort());

            try {
                //得到打印流，用于数据输出，服务器返回数据使用
                PrintStream socketOutput = new PrintStream(socket.getOutputStream());
                //得到输入流
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                do {
                    String str = socketInput.readLine();
                    if ("bye".equalsIgnoreCase(str)) {
                        //回送
                        socketOutput.println("bye");
                        flag = false;
                    } else {
                        //收到消息则打印，并回送数据长度
                        System.out.println(str);
                        socketOutput.println("回送：" + str.length());
                    }
                } while (flag);

            } catch (Exception e) {
                System.out.println("连接异常断开");
            }finally {
                //连接关闭
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                System.out.println("客户端已关闭:"+socket.getInetAddress()+"\n"+"port:"+socket.getPort());
            }
        }
    }
}
